package packing;
import java.io.File;
import java.util.Arrays;

import javax.tools.JavaCompiler;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;

/**
 * The Compile class will compile a java source file into a class file
 * 
 * @see "Java 6 Platform Revealed by John Zukowski"
 */
public class Compile
{
	/**
	 * A static method to compile a given java source file into its class file
	 * 
	 * @param filename
	 *            The name of the java source file
	 * @param outDir
	 *            The output directory of the class file
	 */
	public static void generateClassFile(String filename, String outDir)
	{
		try
		{
			JavaCompiler jc = ToolProvider.getSystemJavaCompiler();

			StandardJavaFileManager sjfm = jc.getStandardFileManager(null,
					null, null);

			File javacode = new File("/tmp/ape", filename);

			Iterable<? extends javax.tools.JavaFileObject> codeObject = sjfm
					.getJavaFileObjects(javacode);

			String[] option = new String[]
			{ "-d", outDir };

			jc.getTask(null, sjfm, null, Arrays.asList(option), null,
					codeObject).call();
			System.out.println(outDir);
			
			
			// Java 6 Platform Revealed by John Zukowski
			// This part can be use to search for the main of 
			// a class a run it
			
			// Class.forName("Number").getDeclaredMethod("main",
			// new Class[] {String[].class}).invoke(null, new Object[] {null});

			// Class.forName("Number").getDeclaredMethod("main",
			// new Class[] {String[].class}).invoke(null, new Object[] {"1"});
			/*
			 * Class cls = Class.forName("Number"); //Name of the class to load
			 * 
			 * Method meth = cls.getMethod( //Name of method, and its argument
			 * "main", String[].class); Object arglist[] = new Object[1];
			 * //Argument list for method arglist[0] = new String[] {"37"};
			 * meth.invoke(null, arglist);
			 */
			sjfm.close();

		} catch (Exception e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
